/*
 * @Descripttion: 
 * @version: 
 * @@Company: 
 * @Author: Crystal
 * @Date: 2021-04-04 09:46:56
 * @LastEditors: Crystal
 * @LastEditTime: 2021-04-04 14:22:19
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>

#include "mqtt_test.h"

#define LOG_TAG "main"
#include "elog.h"
#include "elog_start.h"

#define SEND_MAX_CNT (10)

/**
 * @brief  
 * @note   
 * @retval 
 */
int main(void)
{
    int ret, value;
    uint8_t payload[24] = "temperature: 23.5";
    int payloadlen = strlen(payload);
    int i = 0;

    elog_init_start(); // 配置并启动elog

    if (tcp_connect() < 0) // 创建socket,建立TCP连接
    {
        return -1;
    }

    if (mqtt_conn() < 0) // 连接MQTT服务器
    {
        return -1;
    }

    start_mqtt_heartbeat_thread(); // 启动心跳线程

    mqtt_subscribe_msg(); // 订阅主题

    start_mqtt_recv_thread(); // 启动接收线程

    srand(time(NULL));

    while (1)
    {
        mqtt_publish_msg(payload, payloadlen);

        i++;
        value = rand() % 100 + 200;
        payload[13] = value / 100 + '0';
        payload[14] = value / 10 % 10 + '0';
        payload[16] = value % 10 + '0';

        sleep(5); // 睡眠

        if (i >= SEND_MAX_CNT) // 发送次数
            break;
    }

    mqtt_unsubscribe(); // 取消订阅
    mqtt_disconnect();  // 断开MQTT连接
    tcp_disconnect();   // 断开TCP连接

    return 0;
}
